package com.rfsp.common.config;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 可以在连接上携带区域信息
 */
@Component
public class AppLocaleResolver implements org.springframework.web.servlet.LocaleResolver {

	Locale myLocal = Locale.CHINA;

	/**
	 * 解析区域信息,通过参数
	 * 
	 * @param request
	 * @return
	 */
	public Locale resolveLocale2(HttpServletRequest request) {
		// 获取连接路径上的l后的值 l=zh_CN or en_US
		String lang = request.getParameter("lang");

		// 如果有值则进行语言切换
		if (StringUtils.hasText(lang)) {
			String[] split = lang.split("_");
			myLocal = new Locale(split[0], split[1]);
		}
		return myLocal;
	}

	/**
	 * 通过cookie存储区域语言信息
	 */
	@Override
	public Locale resolveLocale(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies(); // 获取cookie数组
		String lang = "";
		if(cookies!=null)
		for (Cookie cookie : cookies) {
			// 遍历cookie数组
			if ("ClientLanguage".equals(cookie.getName())) {
				lang = cookie.getValue();
				break;
			}
		}
//		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		if (StringUtils.hasText(lang)) {
			if (lang.equals("zh")) {
				myLocal = Locale.CHINA;
			} else if (lang.equals("en")) {
				myLocal = Locale.US;
			} else if (lang.equals("ja")) {
				myLocal = Locale.JAPAN;
			}
		}
		return myLocal;
	}

	@Override
	public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

	}
}